package net.gz01.wallet.web.controller.admin;


import java.io.File;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.upload.UploadFile;

import net.gz01.util.ZODate;
import net.gz01.util.ZOFile;
import net.gz01.util.ZOString;
import net.gz01.util.ZOZIP;
import net.gz01.wallet.common.PageRespon;
import net.gz01.wallet.common.ZOIDGenerate;
import net.gz01.wallet.common.ZOSearchCondition;
import net.gz01.wallet.web.config.SystemConfig;
import net.gz01.wallet.web.config.SystemEnum.FilePath;
import net.gz01.wallet.web.controller.BaseController;
import net.gz01.wallet.web.model.Account;
import net.gz01.wallet.web.model.Merch;
import net.gz01.wallet.web.model.MerchRole;
import net.gz01.wallet.web.model.MerchUser;
import net.gz01.wallet.web.model.Org;
import net.gz01.wallet.web.model.TradeConfig;
import net.gz01.wallet.web.model.YouliAccountRule;
import net.gz01.wallet.web.service.Md5SaltUtil;

public class MerchController extends BaseController {

	public void search(){
		render("merch/merchList.html");
	}

	public void listJson() {
		ZOSearchCondition sc = super.getSearchCondition();
		Page<Merch> pageResult = Merch.dao.search(sc);
		renderJson(new PageRespon(pageResult));
	}

	public void lookup() {
		Page<Merch> items = Merch.dao.search(super.getSearchCondition());
		setPageResultToRequest("items", items);
		render("merch/merchLookup.html");
	}

	public void addPage(){
		//setAttr("orgList", Org.dao.selectToRedis());
		setAttr("youliAccountRuleList", YouliAccountRule.dao.selectAll());
		render("merch/merchAdd.html");
	}

	@Before(Tx.class)
	public void add(){
		String userName = getPara("userName");
		String password = getPara("password");

		Merch merch = getModel(Merch.class, true);
		if (StrKit.isBlank(merch.getCode())) {
//			if("1".equals(merch.getUserType())){//消费者
//				merch.setCode(ZOIDGenerate.getNextMerchCode(false));
//			}else {//商家
//				merch.setCode(ZOIDGenerate.getNextMerchCode(true));
//			}

			merch.setTempCode(ZOIDGenerate.getSerialNumber());
			merch.setCode(merch.getTempCode());

		}
		if(0 < merch.getShopYLAccountRuleId()){
			YouliAccountRule youliAccountRule = YouliAccountRule.dao.findById(merch.getShopYLAccountRuleId());
			if(youliAccountRule.getYouliAccountId().contains(",")){
				renderFail("商城收款卡的规则必须只有一张收款卡");
				return;
			}
		}
		if(StrKit.isBlank(merch.getOrgCode())){
			merch.setOrgCode(SystemConfig.config.get("org_code"));
		}
		merch.setEnable(true);
		merch.setCreateTime(ZODate.getDateTime());
		merch.setMerchNamePy(ZOString.convertStartPinyin(merch.getName()));
		merch.save();

		// TODO 保存默认商户用户
		MerchUser merchUser = new MerchUser();
		merchUser.setUserName(userName);
		merchUser.setPhone(userName);
		merchUser.setUserType(merch.getUserType());
		merchUser.setPassword(Md5SaltUtil.getEncryptedPwd(password));
		merchUser.setName(merch.getName());
		merchUser.setEnable(true);
		merchUser.setMerchCode(merch.getCode());
		merchUser.setTempCode(merch.getTempCode());
		merchUser.setOrgCode(merch.getOrgCode());
		merchUser.setUpdateTime(ZODate.getDateTime());
		MerchRole role = MerchRole.dao.selectByRoleName("商户管理员");
		merchUser.setRoleId(role.getId());
		merchUser.save();

//		if(merch.getIsSign()!=null && merch.getIsSign()) {
//			Account ac = new Account();
//			ac.setAccountNo(merch.getCode());
//			ac.setAccountName(merch.getName());
//			ac.setBalance(0L);
//			ac.setEnable(true);
//			ac.setCreateDateTime(ZODate.getDateTime());
//			ac.save();
//
//			//使用默认的手续费，风控规则，渠道编号保存交易策略
//			TradeConfig.dao.autoCreate(merch.getCode());
//		}
		renderSuccess();
	}

	public void updatePage(){
		Merch merch =  Merch.dao.findById(getPara("id"));
		setAttr("merch",merch);
		setAttr("orgList", Org.dao.selectToRedis());
		setAttr("youliAccountRuleList", YouliAccountRule.dao.selectAll());
		MerchUser user = MerchUser.dao.selectByMerCode(merch.getCode());
		setAttr("user", user);
		render("merch/merchUpdate.html");
	}

	public void update(){
		Merch merch = getModel(Merch.class, true);
		merch.setUpdateTime(ZODate.getDateTime());

		if(0 < merch.getShopYLAccountRuleId()){
			YouliAccountRule youliAccountRule = YouliAccountRule.dao.findById(merch.getShopYLAccountRuleId());
			if(youliAccountRule.getYouliAccountId().contains(",")){
				renderFail("商城收款卡的规则必须只有一张收款卡");
				return;
			}
		}
		merch.update();

		String userName = getPara("user.userName");
		MerchUser merchUser = MerchUser.dao.selectByMerCode(merch.getCode());
		merchUser.setUserName(userName);
		merchUser.update();

		Account account = Account.dao.select(merch.getCode());
		account.setAccountName(merch.getName());
		account.update();
		renderSuccess();
	}

	public void view(){
		Merch merch = Merch.dao.findById(getPara("id"));
		Org org = Org.dao.selectByOrgCode(merch.getOrgCode());
		MerchUser user = MerchUser.dao.selectByMerCode(merch.getCode());

		//获取图片列表
		String merchDataPath = FilePath.MerchData.getValue() + merch.getCode();
		File merchDataFileDir = new File(merchDataPath);
		if(!merchDataFileDir.exists()){
			merchDataFileDir.mkdirs();
		}
		String[] fileNameList = merchDataFileDir.list();
		setAttr("fileNameList", fileNameList);
		setAttr("org", org);
		setAttr("merch", merch);
		setAttr("user", user);
		YouliAccountRule youliAccountRule =  YouliAccountRule.dao.findById(merch.getYouliAccountRuleId());
		if(null != merch.getShopYLAccountRuleId() && 0 < merch.getShopYLAccountRuleId()) {
			YouliAccountRule shopYouliAccountRule = YouliAccountRule.dao.findById(merch.getShopYLAccountRuleId());
			setAttr("shopYouliAccountRule", shopYouliAccountRule);
		}
		setAttr("youliAccountRule", youliAccountRule);
		render("merch/merchViewNew.html");
	}

	public void fileList(){
		Merch merch = Merch.dao.findById(getPara("id"));
		String merchDataPath = FilePath.MerchData.getValue() + merch.getCode();
		File merchDataFileDir = new File(merchDataPath);
		String[] fileNameList = merchDataFileDir.list();
		if(fileNameList != null){
			String fileName = "";
			for (String tmp : fileNameList) {
				fileName += "," + File.separator + merch.getCode() + File.separator + tmp;
			}
			setAttr("fileNames", fileName);
		}
		setAttr("merch", merch);
		render("merch/merchFileList.html");
	}

	public void removeFile(){
		String fileName = getPara("key");
		Boolean isAdd = getParaToBoolean("isAdd");
		String merchDataPath = FilePath.MerchData.getValue() + File.separator + fileName;
		if(isAdd != null && isAdd){
			merchDataPath = FilePath.UploadTmp.getValue() + File.separator + fileName;
		}
		ZOFile.deleteFile(merchDataPath);
		renderSuccess();
	}

	public void showFile(){
		String fileName = getPara("fileName");
		String merchCode = getPara("merchCode");
		String filePath = FilePath.MerchData.getValue() + merchCode + File.separator + fileName;
		if(StrKit.notBlank(fileName)){
			//super.renderStream(filePath);
			renderFile(new File(filePath));
		}else{
			renderNull();
		}
	}

	public void uploadFile(){
		List<UploadFile> files = getFiles();
		String merchCode = getPara("merchCode");
		String merchDataPath = FilePath.MerchData.getValue() + File.separator + merchCode + File.separator;
		ZOFile.mkdir(merchDataPath);

		//处理文件
		for (UploadFile uploadFile : files) {
			uploadFile.getFile().renameTo(new File(merchDataPath + uploadFile.getFileName()));
			uploadFile.getFile().delete();
		}

		renderSuccess();
	}

	public void downloadFile() throws Exception{
		String merchCode = getPara("merchCode");
		String merchDataPath = FilePath.MerchData.getValue() + File.separator + merchCode;
		String zipName = "商户资料(" + merchCode + ").zip";
		ZOZIP.zip(merchDataPath, FilePath.Zip.getValue() + zipName);
		renderFile(new File(FilePath.Zip.getValue() + zipName));
	}

	public void delete(){
		Merch merch = Merch.dao.findById(getPara("id"));
		Account account = Account.dao.select(merch.getCode());
		if (account.getBalance() > 0L) {
			renderFail("该商户还有虚账余额，无法删除");
			return;
		}
		account.delete();
		merch.delete();
		renderSuccess();
	}

	public void downmerch() {
		String merchCode = getPara("code");
		String merchDataPath = FilePath.MerchData.getValue() + File.separator + merchCode;
		String zipName = "商户资料(" + merchCode + ").zip";

		File file = new File(FilePath.Zip.getValue());
		if(!file.exists()) {ZOFile.mkdir(FilePath.Zip.getValue());}

		try {
			ZOZIP.zip(merchDataPath, FilePath.Zip.getValue() + zipName);
			renderFile(new File(FilePath.Zip.getValue() + zipName));
		}catch (Exception e){
			e.printStackTrace();
			renderFail();
		}
	}


	public void uploadmerch() {
		String merchCode = getPara("code");
		setAttr("merchCode", merchCode);
		render("merch/merchUpload.html");
	}


	public void morecz(){
		String merchCode = getPara("code");
		Merch merch = Merch.dao.selectByMerchCode(merchCode);
		if(merch!=null && merch.getCode()!=null){
			setAttr("merch", merch);
			render("merch/merchMore.html");
		}else {
			renderHtml("商户号:" + merchCode + "不存在!!!");
		}
	}

	public void autocomplete() {
		ZOSearchCondition sc = super.getSearchCondition();
		String keywords = sc.getStr("keywords");
		List<Merch> merchList = Merch.dao.autocomplete(keywords);
		JSONObject j = new JSONObject();
		j.put("type", "success");
		j.put("code", "0");
		j.put("content", merchList);
		renderJson(j);
	}


}
